<?php

namespace app\api\controller;

use addons\ymyauexpress\library\Express;
use addons\ymyaws\library\Aws;
use addons\ymypaylinx\library\Paylinx;
use app\admin\model\wanlshop\Packagerule;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\UploadAliyun;
use app\common\model\Config;
use app\common\model\UserGroup;
use app\index\model\wanlshop\Shop;
use biz\modules\mall\models\MallOrder;
use fast\Package;
use fast\Random;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Db;
use think\Request;
use PHPExcel_IOFactory;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public function aliupload(){
        $file = "uploads/20210604/de202375934080a45786901ad006703c.jpg";
        $savekey = $file;



        $upload = [];
        try {
            $ossClient = new OssClient(config("aliyun_oss.access_id"), config("aliyun_oss.access_secret"), config("aliyun_oss.endpoint"));
            $res = $ossClient->uploadFile(config("aliyun_oss.bucket"), $savekey, $file);
            if ($res == null) {
                throw new UploadException(__('No file upload or server upload limit exceeded'));
            }

            $upload["url"] = $res["info"]["url"];
            $upload["etag"] = $res["etag"];
            $upload["oss-request-url"] = $res["oss-request-url"];
            $upload["request-id"] = $res["x-oss-request-id"];
            $upload["Content-Type"] = $res["oss-requestheaders"]["Content-Type"];
        } catch (\Exception $e) {

            throw $e;
        }

        echo "aaa";die;


    }
    public function test(){

    }
    //批量发货，批量改变订单状态
    public function import(){
//        if(empty($_FILES['csv'])){
//            return $this->message('请上传excel文件',['list'],'error');
//        }
        echo "禁用";die;
       // $ar = explode(".",$_FILES['csv']['name']);
        $filename = "./goods.xls";
        if(!is_file($filename)){
            echo "文件不存在"; die;
        }

        $ar = explode(".",$filename);
        $ext = end($ar);
        if (!in_array($ext, [ 'xls', 'xlsx'])) {
            return $this->message('请上传excel文件', ['list'], 'error');
        }



        $objPHPExcel = PHPExcel_IOFactory::load($filename);

        //选择标签页
        $sheet = $objPHPExcel->getSheet(0);
        $total_line =  $sheet->getHighestRow();//总行数
        $total_column = $sheet->getHighestColumn();//总列数


        Db::startTrans();
        try{
            for ($i = 2; $i <= $total_line; $i++){
                $sn = $sheet->getCell('B'.$i)->getValue();
                $name = $sheet->getCell('C'.$i)->getValue();
                $weight = $sheet->getCell('D'.$i)->getValue();
                $price1 = $sheet->getCell('E'.$i)->getValue();
                $price2 = $sheet->getCell('F'.$i)->getValue();
                $group_price1 = $sheet->getCell('G'.$i)->getValue();
                $group_price2 = $sheet->getCell('H'.$i)->getValue();
                $group_price3 = $sheet->getCell('I'.$i)->getValue();
                $stock = $sheet->getCell('J'.$i)->getValue();
                if(empty($name)) continue;

                if(is_object($sn)){
                    $sn = $sn->__toString();
                }
                if(is_object($name)){
                    $name = $name->__toString();
                }
                if(is_object($weight)){
                    $weight = $weight->__toString();
                }
                if(is_object($price1)){
                    $price1 = $price1->__toString();
                }
                if(is_object($price2)){
                    $price2 = $price2->__toString();
                }
                if(is_object($group_price1)){
                    $group_price1 = $group_price1->__toString();
                }
                if(is_object($group_price2)){
                    $group_price2 = $group_price2->__toString();
                }
                if(is_object($group_price3)){
                    $group_price3 = $group_price3->__toString();
                }
                if(is_object($stock)){
                    $stock = $stock->__toString();
                }
                $weight = trim($weight);
                $sn = trim($sn);

                $stock = (int)$stock;
                $name = trim($name);
                $weight = sprintf("%.2f",$weight/1000);
                $price1 = sprintf("%.2f",$price1);
                $price2 = sprintf("%.2f",$price2);
                $group_price1 = sprintf("%.2f",trim($group_price1));
                $group_price2 = sprintf("%.2f",trim($group_price2));
                $group_price3 = sprintf("%.2f",trim($group_price3));

                $goods_data=[
                    'title'=>$name,
                    "price"=>$price2,
                    "market_price"=>$price2,
                    "supply_price"=>$price1,
                    'weight'=>$weight,
                    'stocks'=>$stock,
                ];

                $goods_model = new \app\admin\model\wanlshop\Goods;
                $res = $goods_model->allowField(true)->save($goods_data);
                if(empty($res)){
                    throw new \Exception("goods插入失败：i".$i);
                }

                if(empty($sn)){
                    $t = microtime(true);
                    $t_ar = explode(".",$t);
                    $sn = join("",$t_ar);
                }

                $goods_id = $goods_model->id;

                $group_price = [["group_id"=>1,"price"=>$group_price1],["group_id"=>2,"price"=>$group_price2],["group_id"=>3,"price"=>$group_price3]];
                $sku_data = [
                    "goods_id"=>$goods_id,
                    "group_price"=>json_encode($group_price),
                    "price"=>$price2,
                    "market_price"=>$price2,
                    "supply_price"=>$price1,
                    "stock"=>$stock,
                    'weigh'=>$weight,
                    'sn'=>$sn,
                    "createdtime"=>time()
                ];

                $sku_model = new \app\index\model\wanlshop\GoodsSku;
                $res = $sku_model->allowField(true)->save($sku_data);
                if(empty($res)){
                    throw new \Exception("goods_sku插入失败：i".$i);
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw $e;
        }


        echo "导入成功 $i";die;




    }

    /**
     * 首页
     *
     */
    public function index()
    {
        model('app\index\model\wanlshop\Goods')->updateGoodsSku(86);
        exit;

        $config = model('app\api\model\wanlshop\ShopConfig')->getPayConfig('paylinx_wechat','app',2);
        dump($config);exit;
        $paylinx = Paylinx::wechat($config);
        //支付
        /*$res = $paylinx->scan([
            'out_trade_no'=>Random::alnum().time(),
            'body'=>'xxxxxx',
            'total_fee'=>1000,
            'fee_type'=>'AUD',
            'notify_url'=>$this->request->domain(),
            'return_url'=>$this->request->domain(),
        ]);
        dump($res);exit;*/
        //查询汇率
        /*$params = [
            'fee_type' => 'AUD',
        ];
        $rate = $paylinx->exchangeRate($params);
        dump($rate);*/
        // 查询订单状态
        /*$params = [
            'out_trade_no' => 'HcjOYA1624521118',
        ];
        $res = $paylinx->find($params);
        dump($res['trade_state'] == 'SUCCESS');*/
        // 退款
        /*$params = [
            'out_trade_no' => 'HcjOYA1624521118',
            'out_refund_no' => 'HcjOYA1624521118',
            'refund_fee' => 1000,
            'total_fee' => 1000,
        ];
        $res = $paylinx->refund($params);
        dump($res);*/

        // 退款查询
        /*$params = [
            'out_refund_no' => 'HcjOYA1624521118',
        ];
        $res = $paylinx->findRefund($params);
        dump($res);*/
    }


    public function alipay(){
        // app支付
       $config = [
            'mch_id'=>'201700001363',
            'store_id'=>'2829',
            'key'=>'rx9jwu0Wb9sUPHI7J0DKiIHmUrofKH9i',
            'refer_url'=>$this->request->domain(),
        ];
        $paylinx = Paylinx::alipay($config);
        /*$params = [
           'out_trade_no' => Random::alnum().time(),
           'subject' => '订单支付',
           'notify_url' => $this->request->domain(),
           'total_fee' => 2,
           'trans_currency' => 'AUD',
           'goods_info' => 'pencil^2|eraser^5|iPhone XS 256G^1',
           'total_quantity' => 8,
       ];
       $res = $paylinx->app($params);
       dump($res);exit;*/

        //扫码支付
        /*$params = [
            'out_trade_no' => Random::alnum().time(),
            'subject' => '订单支付',
            'notify_url' => $this->request->domain(),
            'total_fee' => 2,
            'trans_currency' => 'AUD',
        ];
        $res = $paylinx->scan($params);
        dump($res);*/
        //web支付
        /*$params = [
            'out_trade_no' => Random::alnum().time(),
            'subject' => '订单支付',
            'notify_url' => $this->request->domain(),
            'return_url' => $this->request->domain(),
            'total_fee' => 2,
            'trans_currency' => 'AUD',
        ];
        $res = $paylinx->web($params);
        dump($res);*/

        //h5支付
        /*$params = [
            'out_trade_no' => Random::alnum().time(),
            'subject' => '订单支付',
            'notify_url' => $this->request->domain(),
            'return_url' => $this->request->domain(),
            'total_fee' => 2,
            'trans_currency' => 'AUD',
        ];
        $res = $paylinx->h5($params);
        echo $res;*/
        //查询订单状态
        /*$params = [
            'out_trade_no' => '20210624180651607031550789',

        ];
        $res = $paylinx->find($params);
        dump($res) ;*/

        //查询汇率
        /*$params = [
            'fee_type' => 'AUD',

        ];
        $res = $paylinx->exchangeRate($params);
        dump($res);exit;*/

        //申请退款
        $params = [
            'out_trade_no' => '20210624180651607031550789',
            'out_refund_no' => Random::alnum().time(),
            'refund_amount' => 200,
        ];
        $res = $paylinx->refund($params);
        dump($res);exit;

    }

    public function sms(){
        model('app\index\model\wanlshop\Goods')->updateGoodsSku(41);
    }

    public function express(){
        $data['id'] = 59;
        $data['shop_id'] = 2;
        $data['express_no'] = 'ZZ01111000443';
        $address = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $data['id'], 'shop_id' => $data['shop_id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name,number,image_front,image_back')
            ->find();
        $front_file = ROOT_PATH.'/public'.$address['image_front'];
        $front_base64 = base64_encode(file_get_contents($front_file));
        $back_file = ROOT_PATH.'/public'.$address['image_back'];
        $back_base64 =  base64_encode(file_get_contents($back_file));
        $params = [
            "orderId" => 'ZZ01111000443',
            "printMode" => 1,
            "fileType" => 1,
            "fontSize" => 0,
        ];
        $shopConfig = model('app\api\model\wanlshop\ShopConfig')->where('shop_id',$data['shop_id'])->find();
        $express = new Express($shopConfig['au_member_id'],$shopConfig['au_password']);
        $res = $express->print($params);
        dump($res);exit;
    }


    public function package(){
        /*$goods_list = collection(model('app\api\model\wanlshop\OrderGoods')->where('order_id',78)->order('weight','desc')->select())->toArray();
        $rules = collection(Packagerule::all())->toArray();
        $package = new Package($goods_list,$rules);
        $packageList = $package->buildPackage();
        dump($packageList);exit;*/
        exit;
        model('app\api\model\wanlshop\Package')->addPackage(202);
    }

}
